package utils.linkedlist;

/**
 * @author yaohuaiying
 * @create 2018-02-07 15:26
 **/
public class LinkNode {
    private int data;
    private LinkNode next;

    public LinkNode() {
    }

    public LinkNode(int data) {
        this.data = data;
        this.next = null;
    }

    /**
     * 尾部插入
     * @param linkNode
     * @param data
     */
    public void insertNode(LinkNode linkNode, int data){
        if(linkNode.getNext() == null){
            linkNode.setNext(new LinkNode(data));
            return;
        }
        insertNode(linkNode.getNext(), data);
    }

    /**
     * 获取长度
     * @param currentNode
     * @return
     */
    public static int getLength(LinkNode currentNode){
        if(currentNode == null){
            return 0;
        }
        return getLength(currentNode.getNext()) + 1;
    }

    /**
     * 获取第i个node
     * @param currentNode
     * @param i
     * @return
     */
    public static LinkNode getIndex(LinkNode currentNode, int i){
        if(i == 1){
            if(currentNode != null) {
                return currentNode;
            }else {
                throw new RuntimeException("请输入正确的index");
            }
        }else if(i < 1){
            throw new RuntimeException("请输入正确的index");
        }
        return getIndex(currentNode.getNext(),i-1);
    }

    /**
     * 获取尾节点 不考虑环
     * @param linkNode
     * @return
     */
    public static LinkNode getlast(LinkNode linkNode){
        if(linkNode.getNext() == null){
            return linkNode;
        }
        return getlast(linkNode.getNext());
    }

    /**
     * 打印 不考虑又环
     * @param linkNode
     */
    public static void nodePrint(LinkNode linkNode){
        if(linkNode != null){
            System.out.print(linkNode.getData() + "->");
        }
        if(linkNode == null){
            return ;
        }
        nodePrint(linkNode.getNext());
    }

    /**
     * 判断是否有环
     * @param linkNode
     * @return
     */
    public static boolean hasLoop(LinkNode linkNode){
        if(linkNode.getNext() != null) {
            LinkNode fast = linkNode.getNext();
            LinkNode slow = linkNode;
            while (fast.getNext() != null && fast != null) {
                if (fast == slow) {
                    return true;
                }
                if (fast.getNext().getNext() == null || fast.getNext() == null) {
                    return false;
                }
                fast = fast.getNext().getNext();
                slow = slow.getNext();
            }
            return false;
        }else{
            if(linkNode == linkNode.getNext()){
                return true;
            }
            return false;
        }
    }


    public int getData() {
        return data;
    }

    public void setData(int data) {
        this.data = data;
    }

    public LinkNode getNext() {
        return next;
    }

    public void setNext(LinkNode next) {
        this.next = next;
    }
}
